<? // login

// if already logged in, log out
if( $_SESSION['login_ts'] ) {

	// update db with logout
	db_dml( "update users set logout_ts = current_timestamp where usr_id={$_SESSION['usr_id']}" );

	// clear session login info
	$_SESSION['usr_id'] = null;
	$_SESSION['login'] = null;
	$_SESSION['name'] = null;
	$_SESSION['login_ts'] = null;
}

// todo: decrypt pwd
$login = pure_code($_GET['username'] );
$pwd =$_GET['cancel'];
if( !$login or !$pwd ) ajax_exit( 'error', "must have login=$login and password=***" );
$usr_id = db_login( $login, $pwd );
if( !$usr_id ) {
	$schema = db_get_col( "select database()" );
	$usr_id = db_get_col( "select usr_id from users where login='$login'" );
	$ct = db_get_col( "select 1 from users" );
	ajax_exit( 'error', "login or password incorrect.  schema=$schema, usr_id=$usr_id, ct=$ct", array( 'login'=>null, 'name'=>null, 'login_ts'=>null ) );
}
$usr_rcd = db_get_rcd( "select * from users where usr_id=$usr_id" );

// set session
$_SESSION['login'] = $usr_rcd['login'];
$_SESSION['usr_id'] = $usr_rcd['usr_id'];
$_SESSION['name'] = $usr_rcd['name'];
$_SESSION['superuser'] = $usr_rcd['superuser'];
$_SESSION['admin'] = $usr_rcd['admin'];
$_SESSION['login_ts'] = time();
db_dml( "update users set login_ts=current_timestamp where usr_id=$usr_id" );
ajax_exit( 'success', "welcome {$_SESSION['name']}", array(
		'login'=>$_SESSION['login'],
		'name'=>$_SESSION['name'],
		'superuser'=>$_SESSION['superuser'],
		'admin'=>$_SESSION['admin']) );


?>
